package top.chukongxiang.project.base.exception.oauth2;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
import org.springframework.security.oauth2.provider.error.WebResponseExceptionTranslator;
import top.chukongxiang.project.base.model.response.R;

/**
 * /oauth/token 异常处理
 */
@Slf4j
public class MyWebResponseExceptionTranslator implements WebResponseExceptionTranslator {

//    @Override
//    public ResponseEntity<T> translate(Exception e) {
//        if (e instanceof OAuth2Exception) {
//            OAuth2Exception oAuth2Exception = (OAuth2Exception) e;
//            return ResponseEntity
//                    .status(oAuth2Exception.getHttpErrorCode())
//                    .body(R.failed(oAuth2Exception.getMessage()));
//        } else if (e instanceof AuthenticationException) {
//            AuthenticationException authenticationException = (AuthenticationException) e;
//            return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
//                    .body(R.failed(authenticationException.getMessage()));
//        }
//        return ResponseEntity
//                .status(HttpStatus.OK)
//                .body(R.failed(e.getMessage()));
//    }

    @Override
    public ResponseEntity<?> translate(Exception e) {
        if (e instanceof OAuth2Exception) {
            OAuth2Exception oAuth2Exception = (OAuth2Exception) e;
            return ResponseEntity
                    .status(oAuth2Exception.getHttpErrorCode())
                    .body(R.failed(oAuth2Exception.getMessage()));
        } else if (e instanceof AuthenticationException) {
            AuthenticationException authenticationException = (AuthenticationException) e;
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                    .body( R.failed(authenticationException.getMessage()));
        }
        return ResponseEntity
                .status(HttpStatus.OK)
                .body( R.failed(e.getMessage()));
    }
}
